<?php
/**
 * 面向对象的websocket客户端.
 * User: mac
 * Date: 2019-02-28
 * Time: 22:56
 */

class ws
{
    const HOST = '0.0.0.0';
    const PORT = '9502';
    public $ws = null;

    public function __construct()
    {
        //实例化一个websocket服务器
        $this->ws = new swoole_websocket_server(self::HOST, self::PORT);
        //注册open message close 方法
        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);
        //启动服务
        $this->ws->start();
    }

    public function onOpen($ws, $requeset)
    {
        var_dump($requeset);
        $ws->push($requeset->fd, 'hello, welcome' . PHP_EOL);
    }

    public function onMessage($ws, $frame)
    {
        echo 'receive message ' . $frame->data . PHP_EOL;
        $ws->push($frame->fd, 'send message ' . date('Y-m-d H:i:s'));
    }

    public function onClose($ws, $fd)
    {
        echo $fd . ' client close' . PHP_EOL;
    }
}

$ws = new ws();